package com.lantu.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lantu.com.common.vo.Result;
import com.lantu.sys.entity.User;
import com.lantu.sys.mapper.UserMapper;
import com.lantu.sys.service.IUserService;
import com.lantu.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DongJun
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Resource
    private UserMapper userMapper;

    @GetMapping("/list")
    public Result<?> selectAll(@RequestParam(value = "name",required = false) String name){
            List<User> list=userMapper.selectAll(name);
        return  Result.success(list);
    }
    @GetMapping("/login")
    public  Result<User> login(@RequestParam(value = "name",required = false) String  name,
                               @RequestParam(value = "pwd",required = false) String pwd,
                               @RequestParam(value = "role",required = false) String role){
        LambdaQueryWrapper<User> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(User::getName,name);
        wrapper.eq(User::getPwd,pwd);
        wrapper.eq(User::getRole,role);
        User us=userService.getOne(wrapper);
        String token= JwtTokenUtils.sign(us);
       if (us!=null){
           us.setPwd(null);
           return  Result.success(us,"登录成功",token);
       }else {
           return  Result.fail(203,"登录账号和密码或者类型有错误");
       }
    }
    @GetMapping("/selectList")
    public  Result<Map<String,Object>> selectLike(@RequestParam(value = "name",required = false)String name,
                                                  @RequestParam(value = "phone",required = false)String phone,
                                                  @RequestParam(value = "pageNo") Long pageNo,
                                                  @RequestParam(value = "pageSize") Long pageSize){
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name),User::getName,name);
        wrapper.eq(StringUtils.hasLength(phone),User::getPhone,phone);
        Page<User> pages=new Page<>(pageNo,pageSize);
        userService.page(pages,wrapper);
        Map<String,Object> data=new HashMap<>();
        data.put("total",pages.getTotal());
        data.put("rows",pages.getRecords());
        return  Result.success(data);
    }
}
